const app = getApp();
const api = app.globalData.api;
Page({
  data: {
    refreshHeight: 20,
    startY: 0,
    userInfo: {},
    dynamicList: []
  },

  onShow() {
    this.onPullDownRefresh();
  },

  //跳转到上传动态的页面
  toUploadDynamic() {
    wx.navigateTo({
      url: '/pages/uploadDynamic/uploadDynamic',
    })
  },

  //跳转到我的动态页面
  toMyDynamic() {
    wx.navigateTo({
      url: '/pages/myDynamic/myDynamic',
    })
  },

  getAllDynamic() {
    let that = this;
    wx.request({
      url: api + '/user/getAllDynamics',
      method: 'GET',
      success: (res) => {
        console.log(res.data);
        //成功
        if (res.data.code) {
          that.setData({
            'dynamicList': res.data.data
          });
          that.addIsLikeThumb();//增加两个字段，当前用户是否喜欢了，是否点赞了
          that.formatDate();
        }
      },

      fail: (err) => {
        console.log(err);
        wx.showToast({
          title: '动态获取请求出错',
          icon: 'none',
        });
      }
    })
  },

  //修改时间格式
  formatDate() {
    let dynamicList = this.data.dynamicList;
    dynamicList.forEach(element => {
      // 创建一个 Date 对象
      const date = new Date(element.createTime);
      // 获取年、月、日等信息
      const year = date.getFullYear();
      const month = date.getMonth() + 1; // 月份是从 0 开始计数的，需要加 1
      const day = date.getDate();
      const hours = date.getHours();
      const minutes = date.getMinutes();
      const seconds = date.getSeconds();
      // 格式化时间字符串
      // const formattedDate = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hours}:${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
      const formattedDate = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hours}:${minutes < 10 ? '0' + minutes : minutes}`;
      element.createTime = formattedDate;
    });
    this.setData({
      'dynamicList': dynamicList,
    });
  },

  addIsLikeThumb() {
    let tempList = this.data.dynamicList;
    tempList.forEach(item => {
      let isLike = false;
      let isThumb = false;
      let likeList = item.likeList.split(",").filter(function (item) {
        return item !== '';
      });
      let thumbList = item.thumbList.split(",").filter(function (item) {
        return item !== '';
      });

      if (likeList.indexOf(String(this.data.userInfo.id)) != -1) {
        isLike = true;
      }
      if (thumbList.indexOf(String(this.data.userInfo.id)) != -1) {
        isThumb = true;
      }
      item.isLike = isLike;
      item.isThumb = isThumb;
    });
    console.log(this.data.dynamicList);
    this.setData({
      'dynamicList': tempList
    });
  },

  likeDynamic: function (e) {
    // 喜欢动态逻辑
    console.log('喜欢动态');
    let id = e.currentTarget.dataset.id;
    let dynamicList = this.data.dynamicList;
    console.log(id);
    let curDynamic = dynamicList.filter(item => item.id == id);
    let url = '';
    console.log("当前动态==>", curDynamic[0].isLike);
    if (!curDynamic[0].isLike) {
      url = '/user/likeDynamic/';
    } else {
      url = '/user/CancelLikeDynamic/';
    }
    console.log("url==>", url);
    let that = this;
    setTimeout(() => {
      wx.request({
        url: api + url + id + '/' + that.data.userInfo.id,
        method: 'POST',
        success: (res) => {
          console.log(res.data);
          if (res.data.code == 200) {
            let tempList = that.data.dynamicList;
            tempList.forEach(item => {
              if (id == item.id) {
                item.isLike = !item.isLike;
                item.likeNum = res.data.data.likeNum;
              }
            });
            that.setData({
              'dynamicList': tempList
            });
          } else {
            wx.showToast({
              title: '操作失败，出现异常',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          console.log(err);
          wx.showToast({
            title: '操作失败，网络异常',
            icon: 'none'
          })
        }
      })
    }, 200);
  },

  dianzanDynamic: function (e) {
    // 点赞动态逻辑
    console.log('点赞动态');
    let id = e.currentTarget.dataset.id;
    let dynamicList = this.data.dynamicList;
    console.log(id);
    let curDynamic = dynamicList.filter(item => item.id == id);
    let url = '';
    console.log("当前动态==>", curDynamic[0].isThumb);
    if (!curDynamic[0].isThumb) {
      url = '/user/thumbDynamic/';
    } else {
      url = '/user/CancelThumbDynamic/';
    }
    console.log("url==>", url);
    let that = this;
    setTimeout(() => {
      wx.request({
        url: api + url + id + '/' + that.data.userInfo.id,
        method: 'POST',
        success: (res) => {
          console.log(res.data);
          if (res.data.code == 200) {
            let tempList = that.data.dynamicList;
            tempList.forEach(item => {
              if (id == item.id) {
                item.isThumb = !item.isThumb;
                item.thumbNum = res.data.data.thumbNum;
              }
            });
            that.setData({
              'dynamicList': tempList
            });
          } else {
            wx.showToast({
              title: '操作失败，出现异常',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          console.log(err);
          wx.showToast({
            title: '操作失败，网络异常',
            icon: 'none'
          })
        }
      })
    }, 200);
  },

  viewDynamic: function (e) {
    let id = e.currentTarget.dataset.id;
    // 进入动态页面逻辑
    console.log('进入动态页面==>id=', id);
    wx.navigateTo({
      url: '/pages/dynamicInner/dynamicInner?id=' + id,
    });
  },
  onPullDownRefresh: function () {
    // 模拟下拉刷新
    setTimeout(() => {
      this.getAllDynamic();//获取所有动态
      console.log("dynamicList==>", this.data.dynamicList);
      this.setData({
        'userInfo': wx.getStorageSync('loginUser'),
      });
      // 刷新完成后重置下拉区域高度
      this.setData({
        refreshHeight: 20
      });
      wx.stopPullDownRefresh();
    }, 1000);
  },

  touchstart: function (e) {
    this.setData({
      startY: e.touches[0].clientY
    });
  },
  touchmove: function (e) {
    if (e.touches[0].clientY - this.data.startY > 0) {
      this.setData({
        refreshHeight: e.touches[0].clientY - this.data.startY
      });
    }
  },
  touchend: function (e) {
    // 在 touchend 事件中判断是否达到触发下拉刷新的条件
    if (this.data.refreshHeight > 50) {
      this.onPullDownRefresh();
    } else {
      this.setData({
        refreshHeight: 20
      });
    }
  }
});
